package ua.kharkov.knure.mikhaylov.st4.web.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import ua.kharkov.knure.mikhaylov.st4.settings.DataStore;
import ua.kharkov.knure.mikhaylov.st4.settings.LocaleData;

/**
 * Context listener. The sence - to init necessary variables while the context
 * starts
 * 
 * @author Saint
 * 
 */
public class ContextListener implements ServletContextListener {

	private static final Logger log = Logger.getLogger(ContextListener.class);

	public void contextDestroyed(ServletContextEvent event) {
		log.debug("Servlet context destruction starts");
		// do nothing
		log.debug("Servlet context destruction finished");
	}

	public void contextInitialized(ServletContextEvent event) {
		log.debug("Servlet context initialization starts");

		ServletContext servletContext = event.getServletContext();
		initLog4J(servletContext);
		initCommandContainer();
		initDataStore(servletContext);
		initParameters(servletContext);
		initLocale(servletContext);

		log.debug("Servlet context initialization finished");
	}

	/**
	 * Initializes log4j framework.
	 * 
	 * @param servletContext
	 */
	private void initLog4J(ServletContext servletContext) {
		log.debug("Log4J initialization started");
		try {
			PropertyConfigurator.configure(servletContext
					.getRealPath("WEB-INF/log4j.properties"));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		log.debug("Log4J initialization finished");
	}

	/**
	 * Initializes CommandContainer.
	 * 
	 */
	private void initCommandContainer() {

		// initialize commands container
		// just load class to JVM
		try {
			Class.forName("ua.kharkov.knure.mikhaylov.st4.web.command.CommandContainer");
		} catch (ClassNotFoundException ex) {
			throw new RuntimeException(ex);
		}
	}

	private void initDataStore(ServletContext servletContext) {
		try {
			Class.forName("ua.kharkov.knure.mikhaylov.st4.settings.DataStore");
			DataStore.initServletContext(servletContext);
		} catch (ClassNotFoundException ex) {
			throw new RuntimeException(ex);
		}
	}

	private void initParameters(ServletContext servletContext) {
		// Skiping success page - PRG implementation
		servletContext.setAttribute("skipSuccessPage", Boolean
				.valueOf(servletContext.getInitParameter("skipSuccessPage")));
		servletContext.setAttribute("locale",
				servletContext.getInitParameter("locale"));
	}

	private void initLocale(ServletContext servletContext) {
		LocaleData.initResourceBundle(String.valueOf(servletContext
				.getAttribute("locale")));
	}
}